<?php

/* @project : Template
 * @auther  : 青云
 * @date    : 2018/1/10
 * @desc    : 用户控制器
 */

namespace app\admin\controller;

use think\Request;

use app\common\model\Admin as AdminModel;
use app\common\model\User as UserModel;
use app\common\model\Role as RoleModel;

class Admin extends Base
{
    function index(Request $request)
    {
        $role_model = new RoleModel();
        $role_list  = $role_model->getRoleList();
        $this->assign('role_list', $role_list);

        // 如果Ajax 查询并返回数据
        if ($request->isAjax()) {
            if ($request->keyword) {
                $where_user[] = ['name|mobile', 'like', '%' . $request->keyword . '%'];
            }

            if ($request->role_id) {
                $admin_id_list = (new RoleModel())->getAdminIdListByRoleId($request->role_id);
                $where_user[]  = ['id', 'in', $admin_id_list];
            }

            $this->_search_filter($where_user);

            $where_user[] = ['is_del', 'eq', 0];
//            $user_model   = new AdminModel();
            $user_model = (new AdminModel())->withJoin(['roleAdmin'	=> function($query) {
                $roleInfo = (new \app\common\model\Role())->singleData(['name'=>'超级管理员'], 'id');
                $query->where('role_id = '.$roleInfo['id']);
            }]);
            $user_obj     = $this->_list($user_model, $where_user, 'sort asc');

            $this->assign('user_obj', $user_obj);
            return $user_obj;
        } else {
            return $this->fetch();
        }
    }

    function add()
    {
        // 角色数据
        $role_model = new RoleModel();
        $role_list  = $role_model->getRoleList();
        $this->assign('role_list', $role_list);

        return $this->fetch();
    }

    function save(Request $request)
    {
        $controller = $request->controller();

        $path = app()->getAppPath() . '/common/validate/' . $controller . '.php';

        if (file_exists($path)) {
            $validate = validate($controller);
            if (!$validate->check($request->param())) {
                $msg = $validate->getError();
                return $this->api_error($msg, $request->param());
            }
        }
        switch ($request->opmode) {
            case "add" :
                $result   = $this->_insert($request, $controller);
                $admin_id = $result->id;
                $msg      = '新增成功';

                break;

            case "edit" :
                $result   = $this->_update($request, $controller);
                $admin_id = $request->id;
                $msg      = '编辑成功';
                break;

            default :
                $msg    = '非法操作';
                $result = false;
        }

        // 设置角色数据

        $role_id_list = array_filter(explode(',', $request->role_id));

        (new RoleModel())->setRoleListByAdminList([$admin_id], $role_id_list);

        if ($request->isAjax()) {
            if ($result != false) {
                return $this->api_success($msg, $result);
            } else {
                return $this->api_error($msg, $result);
            }
        }
    }

    /** 插入新新数据  **/
    protected function _insert(Request $request, $controller = null)
    {
        if (empty($controller)) {
            $controller = $request->controller();
        }

        $data = $request->param();

        foreach ($data as $key => $item) {
            if (is_array($item)) {
                $data[$key] = implode('|', $item);
            }
        }
        $result = model($controller)->create($data, true);

        return $result;
    }

    /* 更新数据  */
    protected function _update(Request $request, $controller = null)
    {
        if (empty($controller)) {
            $controller = $request->controller();
        }

        $data = $request->param();
        if (empty($data['password'])) {
            unset($data['password']);
        }

        foreach ($data as $key => $item) {
            if (is_array($item)) {
                $data[$key] = implode('|', $item);
            }
        }

        $result = model($controller)->data($data, true)->allowField(true)->force()->isUpdate(true)->save();

        return $result;
    }

    function edit(Request $request)
    {
        // 角色信息列表
        $role_model = new RoleModel();
        $role_list  = $role_model->getRoleList();
        $this->assign('role_list', $role_list);

        $vo = $this->_edit($request);
        return $this->fetch();
    }

    function del(Request $request)
    {
        if (AdminModel::isAdmin($request->id)) {
            return $this->api_error('禁止删除管理员');
        }

        $result = $this->_del($request);
        if ($result != false) {
            return $this->api_success('删除成功');
        } else {
            return $this->api_error('删除失败');
        }
    }

    function sort_up(Request $request)
    {
        return $this->_sort_up($request);
    }

    function sort_down(Request $request)
    {
        return $this->_sort_down($request);
    }

    function set_valid(Request $request)
    {
        $this->_set_valid($request);
    }

    function set_invalid(Request $request)
    {
        if (AdminModel::isAdmin($request->id)) {
            return $this->api_error('不能禁用管理员');
        }
        $this->_set_invalid($request);
    }
}
